<template>
  <div class="employees-container">
    <div class="app-container">
      <!-- 通用工具栏组件使用 -->
      <page-tools>
        <!-- 自定义左侧内容 -->
        <template #slot-left>
          <span>共19条记录</span>
        </template>

        <!-- 自定义右侧内容  prop="staffPhoto" -->
        <template #slot-right>
          <el-button v-power="'import'" type="danger" size="small" @click="$router.push('/excel')">导入excel</el-button>
          <el-button v-power="'export'" type="success" size="small" @click="exportExcelFn">导出excel</el-button>
          <el-button type="primary" size="small" @click="showDialog = true">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px">
        <el-table border :data="employeesList">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像" width="120">
            <template slot-scope="scope">
              <image-holder class="staffPhoto" :src="scope.row.staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column label="手机号" prop="mobile" />
          <el-table-column
            label="工号"
            sortable
            prop="workNumber"
            :sort-method="sortWorkNumberFn"
          />
          <el-table-column v-slot="scope" label="聘用形式">
            <template>
              <span>{{ formatEmployeeFn(scope.row.formOfEmployment) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" />
          <el-table-column label="操作" width="280">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="$router.push('/employees/detail?id=' + scope.row.id)">查看</el-button>
              <el-button type="text" size="small" @click="setEmp(scope.row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="delEmp(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
          <!-- 分页组件 -->
          <el-row
            type="flex"
            justify="center"
            align="middle"
            style="height: 60px"
          >
            <!-- 分页区域 -->
            <el-pagination
              :current-page="query.page"
              :page-sizes="[10, 15, 20, 25]"
              :page-size="query.size"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </el-row>
        </el-table>
      </el-card>
      <el-dialog title="新增员工" :visible.sync="showDialog" @close="dialogClose">
        <emp-form ref="empForm" :tree-data="treeData" @close="formCloseFn" @add-emp="addEmpFn" />
      </el-dialog>

      <!-- 员工-分配角色权限 - 弹窗 -->
      <el-dialog title="分配角色" :visible="showRoleDialog" @close="cancleDialog">
        <!-- 设置角色组件 -->
        <assign-role-dialog ref="roleDialog" :user-id="userId" :role-list="roleList" @close="showRoleDialog = false" @confirm="confirmFn" />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getEmployeeListAPI, getDepartmentsListAPI, addEmployee, getRolesAPI, getUserDetailByIdAPI, assignRolesAPI } from '@/api'
// 树形结构的转换方法
import { transTree } from '@/utils'
import empForm from './components/empDialog.vue'
import AssignRoleDialog from './components/assignRoleDialog.vue'

export default {
  name: 'Employees',
  components: {
    empForm,
    AssignRoleDialog
  },
  data() {
    return {
      query: {
        page: 1, // 页码
        size: 10 // 每页条数
      },
      employeesList: [], // 员工列表
      total: 0, // 数据总条数
      showDialog: false, // 添加员工组件的展示
      treeData: [], // 部门列表数据
      userId: '',
      showRoleDialog: false,
      roleList: []

    }
  },
  created() {
    this.getEmployeeListFn()
    // 调用获取部门列表的方法
    this.getDepartmentsFn()
    this.getRoleListFn()
  },
  methods: {
    // 获取角色列表
    async getRoleListFn() {
      const res = await getRolesAPI()
      this.roleList = res.data.rows
    },
    async getDepartmentsFn() {
      const res = await getDepartmentsListAPI()
      if (!res.success) return this.$message.error(res.message)
      this.treeData = transTree(res.data.depts, '')
      console.log(this.treeData)
    },
    async getEmployeeListFn() {
      const res = await getEmployeeListAPI(this.query)
      console.log(res)
      this.employeesList = res.data.rows
    },
    formatEmployeeFn(str) {
      if (String(str) === '1' || str === '正式') {
        return '正式'
      } else {
        return '非正式'
      }
    },
    sortWorkNumberFn(a, b) {
      return a.workNumber - b.workNumber
    },
    // 每页显示的条数发生改变时触发
    handleSizeChange(newSize) {},

    // 当前页面发生改变时触发
    handleCurrentChange(newPage) {},
    formCloseFn() {
      this.showDialog = false
    },
    async addEmpFn(formData) {
      const res = await addEmployee(formData)
      console.log(res)
    },
    dialogClose() {
      this.$refs.empForm.$refs.addForm.resetFields()
    },
    exportExcelFn() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        // 数据映射数组(顺序)
        const arr = [
          {
            key: 'id',
            name: '序号'
          },
          {
            key: 'username',
            name: '姓名'
          },
          {
            key: 'staffPhoto',
            name: '头像'
          },
          {
            key: 'mobile',
            name: '手机号'
          },
          {
            key: 'workNumber',
            name: '工号'
          },
          {
            key: 'formOfEmployment',
            name: '聘用形式'
          },
          {
            key: 'departmentName',
            name: '部门'
          },
          {
            key: 'timeOfEntry',
            name: '入职日期'
          }
        ]
        // arr筛选头部的字符串数组
        const headerArr = arr.map(obj => obj.name)
        // 遍历整个列表数据(处理)
        const rowsArr = this.employeesList
        const data = rowsArr.map((obj, index) => {
          // 把arr里所有key(英文) -> 统一出来
          const keyArr = arr.map(obj => obj.key)
          // 在从obj里取值,形成一个新的数组
          const value = keyArr.map(enKey => {
            if (enKey === 'id') {
              return index
            } else if (enKey === 'formOfEmployment') {
              const value = obj[enKey]
              if (String(value) === '1' || value === '正式') {
                return '正式'
              } else {
                return '非正式'
              }
            } else {
              return obj[enKey]
            }
          })
          return value // 让当前179行map收集小数组里
        })

        // const tHeader = ['Id', 'Title', 'Author', 'Readings', 'Date']
        // const filterVal = ['id', 'title', 'author', 'pageviews', 'display_time']
        // const data = [[0, '标题', '作者', '读取', '时间']]
        // const list = this.list
        // const data = this.formatJson(filterVal, list)
        excel.export_json_to_excel({
          header: headerArr,
          data,
          filename: '1.xlsx',
          autoWidth: true,
          bookType: 'xlsx'
        })
      })
    },
    // 关闭分配角色弹框
    cancleDialog() {
      this.showRoleDialog = false
      this.$refs.roleDialog.roleIdArr = []
    },
    // 分配角色
    async setEmp(id) {
      this.userId = id
      this.showRoleDialog = true
      const res = await getUserDetailByIdAPI(id)
      this.$refs.roleDialog.roleIdArr = res.data.roleIds
    },
    async confirmFn(roleIdArr) {
      const res = await assignRolesAPI({
        id: this.employeeId,
        roleIds: roleIdArr
      })
      if (res.success) this.$message.error(res.message)
      // 员工分配成功，给用户提示
      this.$message.success(res.message)
      // 关闭弹框
      // 重新获取当前当前列表数据
      this.cancleDialog()
    }
  }
}
</script>

<style lang="scss" scoped>
.staffPhoto {
  width: 100px;
  height: 100px;
  border-radius: 50%;
}
</style>
